<?php
/**
 * 微信红包领取与发送模块微站定义
 *
 * @author cs4du
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

require 'Com/redPack/CommonUtil.class.php';
require 'Com/redPack/MD5SignUtil.class.php';
require 'Com/redPack/SDKRuntimeException.class.php';
require 'Com/redPack/WxHongBaoHelper.class.php';


class Redpacksend_rpModuleSite extends WeModuleSite {

    private $app_id = 'wx927680edc4f2a913'; //微信企业应用的AppID
    private $app_mchid = '1485145522'; //商户号
    private $api_key = '32fa5aDFAfadf45184af3542sfadfa78'; //商户支付密钥Key

    //红包状态
    const PACK_STATUS_DEFAULT   = 0;//未激活
    const PACK_STATUS_ENABLE    = 1;
    const PACK_STATUS_SEND      = 2;
    const PACK_STATUS_ERROR     = 3;

    public function doWebManage() {
        global $_GPC, $_W;
        $pindex = max(1, intval($_GPC['page']));
        $psize = 20;
        $sql = "1";
        $params = array();
        if (isset($_GPC['keywords'])) {
            $sql .= ' AND `activityName` LIKE :keywords';
            $params[':keywords'] = "%{$_GPC['keywords']}%";
        }
        $list = $this->getActivityList($sql, $params, $pindex, $psize, $total);
        $pager = pagination($total, $pindex, $psize);


        include $this->template('manage');
    }


    /**
     * 修改
     */
    public function doWebEdit(){
        include $this->template('form');
    }

    /**
     * 添加
     */
    public function doWebAdd(){
        include $this->template('form');
    }


    private  function assignDo($total,$num,$min,$max){
        $total  *=100;
        $min    *=100;
        $max    *=100;
        
        $avg=$total/$num;

        if($avg==$min || $avg==$max){
            $assignArr=array_fill(0,$num,$avg);
            return $assignArr;
        }

        $assignArr=array_fill(0,$num,$min);
        $left=$total-array_sum($assignArr);

        $i=0;
        while($left>0){
            $rnd=mt_rand(1,min($avg,$left));
            if($assignArr[$i]+$rnd<=$max){
                $assignArr[$i] +=$rnd;
                $left -=$rnd;
            }

            $i=($i+1) % $num;
            if($left<=$avg && $assignArr[$i] +$left<= $max){
                $assignArr[$i] +=$left;
                $left=0;
            }
        }
        return $assignArr;
    }
    public function doWebsave() {
        global $_GPC, $_W;
        $rid = 0;//intval($_GPC['id']);

        $activityName   = $_GPC['activityName'];
        $provider       = $_GPC['provider'];
        $wishing        = $_GPC['wishing'];
        $remark         = $_GPC['remark'];





        $total  = $_GPC['total'];
        $num    = $_GPC['num'];
        $min    = $_GPC['min'];
        $max    = $_GPC['max'];

        $setNum=count($total);

        $totalNum=0;
        $assignArr=array();
        for($i=0;$i<$setNum;$i++){
            $t_total = intval($total[$i]);
            $t_num   = intval($num[$i]);
            $t_min   = intval($min[$i]);
            $t_max   = intval($max[$i]);

            $avg=$t_total/$t_num;

            if($avg<$t_min){
                echo json_encode(array('status'=>1,'msg'=>"第".($i+1)."次分配资金，会小于最小值"));
                die;
            }
            if($avg > $t_max){
                echo json_encode(array('status'=>1,'msg'=>"第".($i+1)."次分配资金，会大于最大值"));
                die;
            }

            $totalNum+=$t_num;

            $assign= $this->assignDo($t_total,$t_num,$t_min,$t_max);
            $assignArr=array_merge($assignArr,$assign);
            unset($assign);

        }


        $assignSet=implode(',',$total).'|'.implode(',',$num).'|'.implode(',',$min).'|'.implode(',',$max);

        $now=time();
        $data=array(
            'activityName'  =>$activityName,
            'provider'      =>$provider,
            'wishing'       =>$wishing,
            'remark'        =>$remark,
            'addTime'       =>$now,
            'assignSet'     =>$assignSet,
            'totalMoney'    =>array_sum($total),
            'num'           =>array_sum($num)
        );








        if ($rid>0){//修改


        }else{//添加
            $result=pdo_insert('redpacksend_rp_activity',$data);
            if ($result===false){
                echo json_encode(array('status'=>1,'msg'=>'添加失败'));
                die;
            }
            $rid=pdo_insertid().'';
            shuffle($assignArr);
            $record=array();
            $sql="insert into ims_redpacksend_rp_prize(activityId,addTime,money,password) values ";

            $totaLen=13;
            $len=$totaLen - strlen($rid)-1;
            require_once 'function.php';
            foreach ($assignArr as $v){
                $pwd = $rid.'W'.great_rand($len);
                $record[]="({$rid},{$now},{$v},'{$pwd}')";
            }
            $sql .=implode(',',$record);
            pdo_run($sql);
        }


        echo json_encode(array('status'=>0,'msg'=>'添加成功'));
        die;
    }

    public function doWebdelete() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);

        if ($rid>0){
            if(pdo_exists("redpacksend_rp_prize",array('activityId'=>$rid,"status >"=>self::PACK_STATUS_ENABLE))){
                message('本活动不可删除，请下线活动！', $this->createWebUrl('manage'), 'failure');
                die;
            }
        }

        if (pdo_delete('redpacksend_rp_activity', array('id' => $rid))) {
            pdo_delete('redpacksend_rp_prize', array('activityId' => $rid));
        }
        message('规则操作成功！', $this->createWebUrl('manage'), 'success');
    }


    public function doWebprizelist() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);
        if (empty($rid)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }


        $where = '';
        $params = array(':rid' => $rid);
        if ($_GPC['status'] != '') {
            $where.=' and status=:status';
            $params[':status'] = intval($_GPC['status']);
        }
        if (!empty($_GPC['keywords'])) {
            $where.=' and password like :keyword';
            $params[':keyword'] = "%{$_GPC['keywords']}%";
        }


        $total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('redpacksend_rp_prize') . " WHERE activityId = :rid " . $where . "", $params);

        $pindex = max(1, intval($_GPC['page']));
        $psize = 10;
        $pager = pagination($total, $pindex, $psize);
        $start = ($pindex - 1) * $psize;
        $limit = " LIMIT {$start},{$psize}";
        $list = pdo_fetchall("SELECT * FROM " . tablename('redpacksend_rp_prize') . " WHERE activityId = :rid " . $where . " ORDER BY id DESC " . $limit, $params);

        include $this->template('prizelist');
    }

    /**
     * 导出清单
     */
    public function doWebdownload() {
        require_once 'download.php';
    }
    public function doWebsetshow() {
        global $_GPC, $_W;
        $rid = intval($_GPC['rid']);
        $isshow = intval($_GPC['isshow']);
        if (empty($rid)) {
            message('抱歉，传递的参数错误！', '', 'error');
        }

        $temp = pdo_update('redpacksend_rp_activity', array('status' => $isshow), array('id' => $rid));
        switch ($isshow){
            case self::PACK_STATUS_DEFAULT:
                pdo_update('redpacksend_rp_prize', array('status' => $isshow), array('activityId' => $rid,'status'=>self::PACK_STATUS_ENABLE));
                break;
            case self::PACK_STATUS_ENABLE:
                pdo_update('redpacksend_rp_prize', array('status' => $isshow), array('activityId' => $rid,'status'=>self::PACK_STATUS_DEFAULT));
                break;
        }

        message('状态设置成功！', $this->createWebUrl('manage'), 'success');
    }


    private function getActivityList($condition = '', $params = array(), $pindex = 0, $psize = 10, &$total = 0){
        if (!empty($condition)) {
            $where = " WHERE {$condition}";
        }
        $sql = "SELECT * FROM " . tablename('redpacksend_rp_activity')  .$where.  " ORDER BY id DESC";
        if ($pindex > 0) {
            $start = ($pindex - 1) * $psize;
            $sql .= " LIMIT {$start},{$psize}";
            $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('redpacksend_rp_activity') . $where, $params);
        }
        return pdo_fetchall($sql, $params);
    }

    private function check_weixin(){
        if (empty($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false) {
            die(json_encode(array('result' => 0, "message" => "您只能在微信客户端参加活动哦!")));
        }
    }

    ///  http://we7/app/index.php?i=2&c=entry&do=index&m=redpacksend_rp
    public function doMobileIndex() {
        if (empty($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false) {
            //die(json_encode(array('result' => 0, "message" => "您只能在微信客户端参加活动哦!")));
            message('您只能在微信客户端参加活动哦!', '', 'error');
        }
        checkauth();
        include $this->template('index');
    }


    public function doMobiledraw(){
        global $_W,$_GPC;
        if (empty($_SERVER['HTTP_USER_AGENT']) || strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false && strpos($_SERVER['HTTP_USER_AGENT'], 'Windows Phone') === false) {
            message('您只能在微信客户端参加活动哦!', '', 'error');
        }
        checkauth();
        $nickname   = $_W['fans']['nickname'];
        $openid     = $_W['fans']['openid'];

        $date= date('Ymd',time());
        $sdate=cache_load('date_'.$openid);
        if(strcmp($date,$sdate)==0){
            $time =cache_load('times_'.$openid) +1;
        }else{
            cache_write('date_'.$openid,$date);
            $time =1;
        }

        if ($time>5){
            message('您已超过尝试次数，请确认兑换码是否正确!', '', 'error');
        }


        $code=$_GPC['code'];

        $codeInfo=pdo_get("redpacksend_rp_prize",array('password'=>$code));
        if(!$codeInfo || $codeInfo['status']!=self::PACK_STATUS_ENABLE){
            cache_write('times_'.$openid,$time);
            message('兑换码不正确，或是已经领取!', '', 'error');
        }

        $activityInfo=pdo_get('redpacksend_rp_activity',array('id'=>$codeInfo['activityId']));
        if(!$activityInfo || $activityInfo['status']!=self::PACK_STATUS_ENABLE){
            message('兑换活动不存在，或未开启!', '', 'error');
        }

        //发奖
        do {
            //组装数据
            $wxHongBaoHelper = new WxHongBaoHelper();
            $wxHongBaoHelper->setParameter("nonce_str", $this->great_rand()); //随机字符串，丌长于 32 位
            $wxHongBaoHelper->setParameter("mch_billno", $this->app_mchid . date('YmdHis') . rand(1000, 9999)); //订单号
            $wxHongBaoHelper->setParameter("mch_id", $this->app_mchid); //商户号
            $wxHongBaoHelper->setParameter("wxappid", $this->app_id);
            $wxHongBaoHelper->setParameter("send_name", $activityInfo['provider']); //红包发送者名称
            $wxHongBaoHelper->setParameter("re_openid", $openid); //用户的openid
            $wxHongBaoHelper->setParameter("total_amount", $codeInfo['money']); //付款金额，单位分
            $wxHongBaoHelper->setParameter("min_value", 100); //最小红包金额，单位分
            $wxHongBaoHelper->setParameter("max_value", 20000); //最大红包金额，单位分
            $wxHongBaoHelper->setParameter("total_num", 1); //红包収放总人数
            $wxHongBaoHelper->setParameter("wishing", $activityInfo['wishing']); //红包祝福语
            $wxHongBaoHelper->setParameter("client_ip", '115.238.128.78'); //调用接口的机器 Ip 地址
            $wxHongBaoHelper->setParameter("act_name", $activityInfo['activityName']); //活动名称
            $wxHongBaoHelper->setParameter("remark", $activityInfo['remark']); //备注信息

            //生成xml并且生成签名
            $postXml = $wxHongBaoHelper->create_hongbao_xml($this->api_key);
            //dump ( $postXml);die();
            //提交请求
            $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
            $responseXml = $wxHongBaoHelper->curl_post_ssl($url, $postXml);

            $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
            //转换成数组
            $responseArr = ( array )$responseObj;

            $return_code = $responseArr ['return_code'];
            $result_code = $responseArr ['result_code'];

            //判断是否红包是否发送成功
            if ($return_code == "SUCCESS" && $result_code == "SUCCESS") {
                pdo_update("redpacksend_rp_prize",array('status'=>self::PACK_STATUS_SEND,'receiveTime'=>time(),'openid'=>$openid),array('password'=>$code));
                message('兑换成功，领奖推送正在发出，请在24小时内领取', '', 'success');
            } else {
                pdo_update("redpacksend_rp_prize",array('status'=>self::PACK_STATUS_ERROR,'receiveTime'=>time()),array('password'=>$code));
                message('红包发送失败，请联系客服处理', '', 'error');
            }
        }while(false);


    }
    //获取随机数
    private function great_rand(){
        $str = '1234567890abcdefghijklmnopqrstuvwxyz';
        $t1='';
        for($i = 0; $i < 30; $i ++) {
            $j = rand ( 0, 35 );
            $t1 .= $str [$j];
        }
        return $t1;
    }
}